package com.ziqi.hututubackend.manager.upload;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import com.ziqi.hututubackend.config.CosClientConfig;
import com.ziqi.hututubackend.exception.BusinessException;
import com.ziqi.hututubackend.exception.ErrorCode;
import com.ziqi.hututubackend.manager.CosManager;
import com.ziqi.hututubackend.model.dto.file.UploadPictureResult;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * 文件上传通用的模版方法
 */
@Slf4j
public abstract class PictureUploadTemplate {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;

    /**
     * 定义模版抽象类，通用流程
     * 1. 校验图片
     * 2. 获取文件名称
     * 3. 保存临时文件
     *
     * @param inputSource      本地图片对象或URL
     * @param uploadPathPrefix 上传路径前缀
     * @return
     */
    public final UploadPictureResult uploadPicture(Object inputSource, String uploadPathPrefix) {
        // 校验图片
        validPicture(inputSource);
        // 图片上传地址
        String uuid = RandomUtil.randomString(16); //随机16字符的占位符
        /** 获取图片名，抽象类 getOriginFilename*/
        String originFilename = getOriginFilename(inputSource);
        // 设置更新后的文件名，格式化  (当前日期 + 随机字符。 + 图片后缀)
        String uploadFilename = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid, FileUtil.getSuffix(originFilename));
        // 设置更新后的文件路径
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFilename);

        File file = null;
        try {
            //1.创建临时文件
            file = File.createTempFile(uploadPath, null);
            /** 处理图片来源，本地或URL获取（抽象类 processFile） */
            processFile(inputSource, file);
            //2.上传原始图片到cos对象存储
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
                // 获取图片信息
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            ProcessResults processResults = putObjectResult.getCiUploadResult().getProcessResults();
            List<CIObject> objectList = processResults.getObjectList();

            CIObject compressdCIObject = new CIObject();
            CIObject thumbnailCIObject = new CIObject();
            if(CollUtil.isNotEmpty(objectList)) {
                // 设置webp格式压缩图
                compressdCIObject = objectList.get(0);
                // 缩略图默认等于压缩图
                thumbnailCIObject = compressdCIObject;
                // 如果有设置缩略图，则单独设置
                if(objectList.size() > 1) {
                    thumbnailCIObject = objectList.get(1);
                }
            }
            // 3.封装所有类型图片返回结果
            return buildResult(originFilename, file, uploadPath, imageInfo, compressdCIObject, thumbnailCIObject);

        } catch (Exception e) {
            log.error("图片上传到对象存储失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
            // 上传完成后删除本地临时文件
        } finally {
            this.deleteTempFile(file);
        }

    }

    /**
     * 校验输入源（本地文件或url
     */
    protected abstract void validPicture(Object inputSource);

    /**
     * 处理输入源生成本地临时文件
     */
    protected abstract void processFile(Object inputSource, File file) throws Exception;

    /**
     * 获取输入源的文件名
     */
    protected abstract String getOriginFilename(Object inputSource);

    /**
     * 删除临时文件
     *
     * @param file
     */
    public void deleteTempFile(File file) {
        if (file == null) return;
        //删除临时文件
        boolean deleteResult = file.delete();
        if (!deleteResult) {
            log.error("文件删除失败，文件路径 = {}", file.getAbsolutePath());
        }
    }

    /**
     * 封装图片返回结果
     *
     * @param originFilename
     * @param file
     * @param uploadPath
     * @param imageInfo
     * @return
     */
    /**
     * 封装图片返回结果
     * @param originFilename  原文件
     * @param file 图片文件对象
     * @param uploadPath 原图上传地址
     * @param imageInfo 图片信息
     * @param compressCiobject webp压缩格式图片对象
     * @param thumbnailCIObject 压缩图片对象
     * @return
     */
    private UploadPictureResult buildResult(String originFilename, File file, String uploadPath, ImageInfo imageInfo, CIObject compressCiobject, CIObject thumbnailCIObject) {
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        uploadPictureResult.setPicName(FileUtil.mainName(originFilename));
        //设置图片宽度
        int picWidth = imageInfo.getWidth();
        uploadPictureResult.setPicWidth(picWidth);
        //设置图片高度
        int picHeight = imageInfo.getHeight();
        uploadPictureResult.setPicHeight(picHeight);
        // 计算图片比例并赋值
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        uploadPictureResult.setPicScale(picScale);
        // 图片格式
        uploadPictureResult.setPicFormat(imageInfo.getFormat());
        // 图片尺寸
        uploadPictureResult.setPicSize(FileUtil.size(file));
        //设置图片主色调
        uploadPictureResult.setPicColor(imageInfo.getAve());
        // 赋值图片url地址, ----- 主机地址 + 相对地址就是绝对地址
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + compressCiobject.getKey());  //用于展示url，原地址或webp地址
        uploadPictureResult.setBaseUrl(cosClientConfig.getHost() + "/" + uploadPath);  // 原图地址
        uploadPictureResult.setThumbnailUrl(cosClientConfig.getHost() + "/" + thumbnailCIObject.getKey()); // 压缩图地址
        return uploadPictureResult;
    }

//    /**
//     * 封装缩略图webp格式图片返回结果
//     *
//     * @param originFilename
//     * @param compressCiobject
//     * @return
//     */
//    private UploadPictureResult buildResult(String originFilename, CIObject compressCiobject, CIObject thumbnailCIObject) {
//        UploadPictureResult uploadPictureResult = new UploadPictureResult();
//        uploadPictureResult.setPicName(FileUtil.mainName(originFilename));
//        //设置图片宽度
//        int picWidth = compressCiobject.getWidth();
//        uploadPictureResult.setPicWidth(picWidth);
//        //设置图片高度
//        int picHeight = compressCiobject.getHeight();
//        uploadPictureResult.setPicHeight(picHeight);
//        // 计算图片比例并赋值
//        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
//        uploadPictureResult.setPicScale(picScale);
//        // 图片格式
//        uploadPictureResult.setPicFormat(compressCiobject.getFormat());
//        // 图片尺寸
//        uploadPictureResult.setPicSize(compressCiobject.getSize().longValue());
//        // 赋值图片url地址, ----- 主机地址 + 相对地址就是绝对地址
//        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + compressCiobject.getKey());
//        uploadPictureResult.setThumbnailUrl(cosClientConfig.getHost() + "/" + thumbnailCIObject.getKey());
//        return uploadPictureResult;
//    }
}
